package com.wjl.mianshiti.blackfilter;

import cn.hutool.bloomfilter.BitMapBloomFilter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

public class BlackIpUtils {

    private static BitMapBloomFilter bitMapBloomFilter;

    public static boolean isBlackIp(String ip) {
        return bitMapBloomFilter.contains(ip);
    }
    public static void rebuildBlackIp(String config) {
        if (StrUtil.isBlank(config)) {
            config = "{}";
        }
        Yaml yaml = new Yaml();
        Map map = yaml.loadAs(config, Map.class);
        List<String> blackIpList = (List<String>) map.get("blackIpList");
        synchronized (BlackIpUtils.class) {
            if (CollUtil.isNotEmpty(blackIpList)) {
                bitMapBloomFilter = new BitMapBloomFilter(958506);
                for (String s : blackIpList) {
                    bitMapBloomFilter.add(s);
                }
            } else {
                bitMapBloomFilter = new BitMapBloomFilter(100);
            }
        }
    }
}
